package cn.schoolwow.quickapi.module.business.api.flow.single;

import cn.schoolwow.quickapi.module.business.api.domain.API;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.lang.reflect.Method;

public class GetByRequestMappingAnnotationFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        setRequestMapping(flowContext);
        setAPI(flowContext);
    }

    @Override
    public String name() {
        return "根据指定方法注解获取API信息";
    }

    private void setRequestMapping(FlowContext flowContext){
        Method method = (Method) flowContext.checkData("method");

        RequestMapping requestMapping = method.getDeclaredAnnotation(RequestMapping.class);
        if(null==requestMapping){
            flowContext.brokenCurrentFlow("不存在RequestMapping注解");
        }
        flowContext.putCurrentFlowData("requestMapping", requestMapping);
    }

    private void setAPI(FlowContext flowContext) {
        RequestMapping requestMapping = (RequestMapping) flowContext.checkData("requestMapping");
        Method method = (Method) flowContext.checkData("method");
        API api = (API) flowContext.checkData("api");

        RequestMethod[] requestMethods = requestMapping.method();
        if(requestMethods.length>0){
            api.requestMethod = requestMethods[0].name().toUpperCase();
        }
        if(requestMapping.value().length>0){
            api.url = requestMapping.value()[0];
        }else{
            api.url = method.getName();
        }
    }
}
